package com.hmkj.core.api.mokapay;

import com.alibaba.fastjson.JSON;
import com.hmkj.common.utils.HttpClientUtils;
import com.hmkj.common.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 默卡支付接口工具类
 *
 * @author eproo
 * @create 2018-05-08 19:26
 */
@Slf4j
public class MokaPayUtils {

    /**
     * 快捷支付
     *
     * @param orderNo
     * @param amount
     * @return
     * @throws Exception
     */
    public static Map<String, String> quickMokaPay(String orderNo, String amount) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String url = "http://www.hhnnm.com/api/v1/orders";
        String key = "64f001d665364edca835cc19f2de84272eac46dc";

//        String userId = ConfigUtils.getProperty("easy_user_id");//商户ID
//        String returnUrl = ConfigUtils.getProperty("easy_return_url");//同步通知地址
//        String notifyUrl = ConfigUtils.getProperty("easy_notify_url");//异步通知地址

        String userId = "11020";
        String returnUrl = "http://www.igo.com/notify.php";
        String notifyUrl = "http://www.igo.com/return.php";
        String gatType = "EasyPay";
        String goodsId = "232";
        params.put("userId", userId);
        params.put("sdorderNo", orderNo);
        params.put("totalFee", amount);
        params.put("gatType", gatType);
        params.put("returnUrl", returnUrl);
        params.put("notifyUrl", notifyUrl);
        params.put("goodsId", "232");
        String paramStr = "gatType=" + gatType + "&goodsId=" + goodsId + "&notifyUrl=" + notifyUrl + "&returnUrl=" + returnUrl + "&sdorderNo=" + orderNo + "&totalFee=" + amount + "&userId=" + userId + "&key=" + key;
//        params.put("sign", signDataStr(paramStr));
        String result = HttpClientUtils.httpPost(url, params);
        System.out.println("默卡支付返回结果：" + result);
        return (Map) JSON.parse(result);
    }

    public static String signDataStr(MokaPaymentInfo paymentInfo) throws Exception {
        String paramStr = "gatType=" + paymentInfo.getGatType() + "&goodsId=" + paymentInfo.getGoodsId() + "&notifyUrl=" + paymentInfo.getNotifyUrl() + "&returnUrl=" + paymentInfo.getReturnUrl() + "&sdorderNo=" + paymentInfo.getSdorderNo() + "&totalFee=" + paymentInfo.getTotalFee() + "&userId=" + paymentInfo.getUserId() + "&key=" + paymentInfo.getKey();
        log.info("摩卡支付待签名数据：{}" , paramStr );
        String signData = MD5Utils.getMd5(paramStr);
        log.info("摩卡支付待签名结果：{}" , signData );
        return signData;
    }

    public static void main(String[] args) throws Exception {

//        quickMokaPay("20180324165932659", "1");
    }

    /**
     * 异步请求数据验签
     *
     * @param mokaNotifyInfo
     * @return
     */
    public static boolean verferSignData(MokaNotifyInfo mokaNotifyInfo) {
        String signatureStr = "customerid="+mokaNotifyInfo.getCustomerid()+"&paytype="+mokaNotifyInfo.getPaytype()+"&sdorderno="+mokaNotifyInfo.getSdorderno()+"&sdpayno="+mokaNotifyInfo.getSdpayno()+"&status="+mokaNotifyInfo.getStatus()+"&total_fee="+mokaNotifyInfo.getTotal_fee()+"&key="+MokaPayConfig.KEY;
        log.info("验签数据：" + signatureStr);
        log.info("数字签名：" + mokaNotifyInfo.getSign());
        return MD5Utils.getMd5(signatureStr).equals(mokaNotifyInfo.getSign());
    }


    public static MokaNotifyInfo buildNotifyParam(HttpServletRequest req) {
        MokaNotifyInfo mokaNotifyInfo = new MokaNotifyInfo();
        String status = req.getParameter("status");//订单支付状态
        String customerid = req.getParameter("customerid");//合作商户的商户号
        String sdpayno = req.getParameter("sdpayno");//平台支付订单号
        String sdorderno = req.getParameter("sdorderno");//商户订单编号
        String total_fee = req.getParameter("total_fee");//支付金额(元)
        String paytype = req.getParameter("paytype");//支付类型
        String sign = req.getParameter("sign");//签名串
        mokaNotifyInfo.setStatus(status);
        mokaNotifyInfo.setCustomerid(customerid);
        mokaNotifyInfo.setSdpayno(sdpayno);
        mokaNotifyInfo.setSdorderno(sdorderno);
        mokaNotifyInfo.setTotal_fee(total_fee);
        mokaNotifyInfo.setPaytype(paytype);
        mokaNotifyInfo.setSign(sign);
        return mokaNotifyInfo;
    }


    /**
     * 读取request流
     *
     * @param request request
     * @return String
     * @author guoyx
     */
    public static String readReqStr(HttpServletRequest request) {
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(request
                    .getInputStream(), "utf-8"));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }
        return sb.toString();
    }

}
